<template>
    <div class="mx-auto">
        <!-- 标题 -->
        <!-- <h1 class="text-center text-2xl font-bold text-gray-800">我的个人信息</h1> -->

        <!-- 主卡片 -->
        <!-- <div class="overflow-hidden rounded-xl border border-gray-100 bg-white shadow-sm"> -->
        <a-card>
            <!-- 头部：头像 + 编辑按钮 -->
            <div class="flex flex-col items-start gap-6 border-b border-gray-100 p-6 sm:flex-row sm:items-center">
                <!-- 头像区域 -->
                <div class="relative">
                    <a-avatar
                        :src="userInfo.avatar"
                        :size="96"
                        class="rounded-full border-2 border-gray-100 shadow-sm"
                    />
                    <div
                        class="absolute bottom-0 right-0 flex aspect-square w-10 items-center justify-center rounded-full border border-gray-200 bg-white p-1 opacity-0 shadow-lg transition-opacity duration-200 hover:opacity-100"
                    >
                        <a-upload
                            name="avatar"
                            :show-upload-list="false"
                            :custom-request="handleAvatarUpload"
                            :before-upload="beforeUpload"
                            class="cursor-pointer"
                        >
                            <a-button
                                type="text"
                                size="small"
                                class="rounded-full p-1 text-gray-600 transition-colors hover:bg-gray-50 hover:text-blue-600"
                            >
                                <UploadOutlined class="text-sm" />
                            </a-button>
                        </a-upload>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div class="flex flex-wrap gap-3">
                    <a-button
                        type="primary"
                        @click="isEditing ? handleSave() : startEdit()"
                        :loading="loading"
                        class="rounded-lg text-sm font-medium transition-colors"
                        :class="{
                            'bg-blue-600 text-white hover:bg-blue-700': !isEditing,
                            'bg-green-600 text-white hover:bg-green-700': isEditing
                        }"
                    >
                        {{ isEditing ? "保存更改" : "编辑信息" }}
                    </a-button>
                    <a-button
                        type="default"
                        @click="showPasswordModal = true"
                        class="rounded-lg bg-gray-100 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-200"
                    >
                        修改密码
                    </a-button>
                </div>
            </div>

            <!-- 内容区域 -->
            <div class="p-6">
                <a-form
                    :model="formState"
                    :label-col="{ span: 6 }"
                    :wrapper-col="{ span: 18 }"
                    layout="horizontal"
                    :disabled="!isEditing"
                    class="space-y-6"
                >
                    <!-- 基本信息 -->
                    <div class="border-b border-gray-100 pb-6">
                        <h3 class="mb-4 text-lg font-semibold text-gray-800">基本信息</h3>

                        <a-form-item label="用户名" class="mb-4">
                            <a-input
                                v-if="isEditing"
                                v-model:value="formState.username"
                                placeholder="请输入用户名"
                                class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                            />
                            <div v-else class="font-medium text-gray-700">{{ formState.username }}</div>
                        </a-form-item>

                        <a-form-item label="昵称" class="mb-4">
                            <a-input
                                v-if="isEditing"
                                v-model:value="formState.nickname"
                                placeholder="请输入昵称"
                                class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                            />
                            <div v-else class="font-medium text-gray-700">{{ formState.nickname }}</div>
                        </a-form-item>

                        <a-form-item label="真实姓名" class="mb-4">
                            <a-input
                                v-if="isEditing"
                                v-model:value="formState.realname"
                                placeholder="请输入真实姓名"
                                class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                            />
                            <div v-else class="font-medium text-gray-700">{{ formState.realname }}</div>
                        </a-form-item>

                        <a-form-item label="性别" class="mb-4">
                            <a-radio-group v-if="isEditing" v-model:value="formState.gender" class="flex gap-4">
                                <a-radio value="male" class="text-gray-700">男</a-radio>
                                <a-radio value="female" class="text-gray-700">女</a-radio>
                                <a-radio value="unknown" class="text-gray-700">未知</a-radio>
                            </a-radio-group>
                            <div v-else class="font-medium text-gray-700">
                                {{ formState.gender === "male" ? "男" : formState.gender === "female" ? "女" : "其他" }}
                            </div>
                        </a-form-item>
                    </div>

                    <!-- 联系方式 -->
                    <div class="border-b border-gray-100 pb-6">
                        <h3 class="mb-4 text-lg font-semibold text-gray-800">联系方式</h3>

                        <a-form-item label="邮箱" class="mb-4">
                            <a-input
                                v-if="isEditing"
                                v-model:value="formState.email"
                                placeholder="请输入邮箱"
                                class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                            />
                            <div v-else class="font-medium text-gray-700">{{ formState.email }}</div>
                        </a-form-item>

                        <a-form-item label="手机号" class="mb-4">
                            <a-input
                                v-if="isEditing"
                                v-model:value="formState.phone"
                                placeholder="请输入手机号"
                                class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                            />
                            <div v-else class="font-medium text-gray-700">{{ formState.phone }}</div>
                        </a-form-item>
                    </div>

                    <!-- 系统信息（只读） -->
                    <div class="pb-6">
                        <h3 class="mb-4 text-lg font-semibold text-gray-800">系统信息</h3>

                        <div class="grid grid-cols-1 gap-4 text-sm md:grid-cols-2">
                            <div class="rounded-lg border border-gray-200 bg-gray-50 p-4">
                                <label class="mb-1 block text-gray-500">注册时间</label>
                                <p class="font-medium text-gray-800">{{ userInfo.createdAt }}</p>
                            </div>
                            <div class="rounded-lg border border-gray-200 bg-gray-50 p-4">
                                <label class="mb-1 block text-gray-500">最后登录</label>
                                <p class="font-medium text-gray-800">{{ userInfo.lastLoginAt }}</p>
                            </div>
                            <div class="rounded-lg border border-gray-200 bg-gray-50 p-4">
                                <label class="mb-1 block text-gray-500">用户ID</label>
                                <p class="font-medium text-gray-800">{{ userInfo.id }}</p>
                            </div>
                            <div class="rounded-lg border border-gray-200 bg-gray-50 p-4">
                                <label class="mb-1 block text-gray-500">最后登录IP</label>
                                <p class="font-medium text-gray-800">{{ userInfo.lastLoginIp }}</p>
                            </div>
                        </div>
                    </div>
                </a-form>
            </div>
        </a-card>

        <!-- 修改密码弹窗 -->
        <a-modal
            v-model:open="showPasswordModal"
            title="修改密码"
            ok-text="确认修改"
            cancel-text="取消"
            @ok="handlePasswordChange"
            @cancel="showPasswordModal = false"
            class="max-w-md"
        >
            <a-form
                :model="passwordForm"
                :rules="passwordRules"
                ref="passwordFormRef"
                layout="vertical"
                class="space-y-4"
            >
                <a-form-item label="当前密码" name="oldPassword">
                    <a-input-password
                        v-model:value="passwordForm.oldPassword"
                        placeholder="请输入当前密码"
                        class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                    />
                </a-form-item>

                <a-form-item label="新密码" name="newPassword">
                    <a-input-password
                        v-model:value="passwordForm.newPassword"
                        placeholder="至少6位"
                        class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                    />
                </a-form-item>

                <a-form-item label="确认新密码" name="confirmPassword">
                    <a-input-password
                        v-model:value="passwordForm.confirmPassword"
                        placeholder="请再次输入"
                        class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                    />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { UploadOutlined } from "@ant-design/icons-vue";
import { message, type UploadProps } from "ant-design-vue";
import type { RuleObject } from "ant-design-vue/es/form";
import { onMounted, reactive, ref } from "vue";

import type { SysUserVo } from "@/api/globals";
import { useFileHash } from "@/hooks/useFileHash";
import { useAdminStore } from "@/stores/admin";
import { Feedback } from "@/utils/feedback";

// 修改个人信息DTO类型
interface UpdateUserInfoDTO {
    username: string;
    email: string;
    nickname: string;
    realname: string;
    phone: string;
    gender: "male" | "female" | "unknown";
}

// 状态变量
const loading = ref(false);
const isEditing = ref(false);
const showPasswordModal = ref(false);

const adminStore = useAdminStore();

// 用户信息
const userInfo = ref<SysUserVo>({
    id: 1,
    avatar: "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
    username: "admin",
    nickname: "超级管理员",
    isDisabled: false,
    lastLoginIp: "127.0.0.1",
    lastLoginAt: "2023-01-01 12:00:00",
    createdAt: "2023-01-01 12:00:00",
    updatedAt: "2023-01-01 12:00:00",
    sort: 1,
    isMultipoint: false,
    email: "admin@example.com",
    phone: "13800138000",
    isFixed: false,
    realname: "张三",
    gender: "male"
});

// 表单数据
const formState = reactive<UpdateUserInfoDTO>({
    username: "",
    email: "",
    nickname: "",
    realname: "",
    phone: "",
    gender: "male"
});

// 密码修改表单
const passwordFormRef = ref();
const passwordForm = reactive({
    oldPassword: "",
    newPassword: "",
    confirmPassword: ""
});

// 密码规则
const passwordRules: Record<string, RuleObject | RuleObject[]> = {
    oldPassword: [{ required: true, message: "请输入当前密码", trigger: "blur" }],
    newPassword: [
        { required: true, message: "请输入新密码", trigger: "blur" },
        { min: 6, message: "密码长度至少6位", trigger: "blur" }
    ],
    confirmPassword: [
        { required: true, message: "请再次输入新密码", trigger: "blur" },
        {
            validator: async (_rule: any, value: string) => {
                if (value && value !== passwordForm.newPassword) {
                    return Promise.reject("两次输入的密码不一致");
                }
                return Promise.resolve();
            },
            trigger: "blur"
        }
    ]
};

// 获取用户信息
const fetchUserInfo = async () => {
    loading.value = true;
    try {
        const res = await Apis.SysUser.findSelfUserInfo();

        // 模拟数据（保持一致）
        Object.assign(userInfo.value, res.data);

        // 同步到表单
        Object.assign(formState, {
            username: userInfo.value.username,
            email: userInfo.value.email,
            nickname: userInfo.value.nickname,
            realname: userInfo.value.realname,
            phone: userInfo.value.phone,
            gender: userInfo.value.gender
        });
    } catch (error) {
        Feedback.msgError("获取用户信息失败");
    } finally {
        loading.value = false;
    }
};

// 开始编辑
const startEdit = () => {
    isEditing.value = true;
    // 重置表单为当前值
    Object.assign(formState, {
        username: userInfo.value.username,
        email: userInfo.value.email,
        nickname: userInfo.value.nickname,
        realname: userInfo.value.realname,
        phone: userInfo.value.phone,
        gender: userInfo.value.gender
    });
};

// 保存信息
const handleSave = async () => {
    loading.value = true;
    try {
        // 替换为你的真实接口
        // await updateUserInfoAPI(formState);
        const res =  await Apis.SysUser.updateSelf({
            data: formState
        });

        adminStore.userinfo = res.data;
        Object.assign(userInfo.value, formState);
        Feedback.msgSuccess("个人信息已更新");
        isEditing.value = false;
    } catch (error) {
        Feedback.msgError("保存失败，请重试");
    } finally {
        loading.value = false;
    }
};

// 头像上传前检查
const beforeUpload: UploadProps["beforeUpload"] = file => {
    const allowTypes = ["image/jpeg", "image/png", "image/gif", "image/jpg"];
    const isLegalType = allowTypes.includes(file.type);

    if (!isLegalType) {
        message.error("仅支持 JPG/PNG/GIF/JPEG 格式！");
        return false;
    }
    const isLegalSize = file.size / 1024 / 1024 < 5;
    if (!isLegalSize) {
        message.error("图片大小不能超过 5MB！");
        return false;
    }
    return isLegalType && isLegalSize;
};

const { calculateFileHash } = useFileHash();

// 头像上传处理
const handleAvatarUpload: UploadProps["customRequest"] = async options => {
    try {
        const file = options.file as File;
        const hash = await calculateFileHash(file);
        const res = await Apis.SysUser.uploadAvatar({
            data: {
                dirId: 1,
                origin: "admin",
                hash,
                file
            }
        });
        adminStore.userinfo.avatar = res.data.avatar;

        userInfo.value.avatar = res.data.avatar;
        // const reader = new FileReader();
        // reader.readAsDataURL(file);
        // reader.onload = e => {
        //     userInfo.value.avatar = e.target?.result as string;
        //     Feedback.msgSuccess("头像更新成功");
        // };
    } catch (error) {
        Feedback.msgError("头像上传失败");
    } finally {
    }
};

// 修改密码
const handlePasswordChange = async () => {
    loading.value = true;
    try {
        const values = await passwordFormRef.value.validateFields();
        console.log("values", values);
        await Apis.SysUser.updatePassword({
            data: { oldPassword: values.oldPassword, newPassword: values.newPassword }
        });

        Feedback.msgSuccess("密码修改成功");
        showPasswordModal.value = false;
        passwordFormRef.value?.resetFields();
        Object.assign(passwordForm, { oldPassword: "", newPassword: "", confirmPassword: "" });
    } catch (error) {
        Feedback.msgError("密码修改失败");
    } finally {
        loading.value = false;
    }
};

// 页面初始化
onMounted(() => {
    fetchUserInfo();
});
</script>
